<template>
  <body id="poster">
    <div class="loginPage">
      <h3 class="login-title">欢迎登录</h3>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input  v-model="form.password" placeholder="输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="submit" >登录</el-button>
          <el-button>注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </body>
</template>
  
<script>
import Mock from 'mockjs'
import Cookie from 'js-cookie'
import { getMenu } from '@/api'

export default {
  name: "LoginPage",
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
      rules: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    submit(){
      //校验通过
      this.$refs.form.validate((valid)=>{
        if(valid){
          getMenu(this.form).then(({data})=>{
            // console.log('TTT',data);
            if(data.code === 20000){
              // token信息存入cookie用于不同页面间的通讯
              Cookie.set('token',data.data.token);
              // 获取菜单数据，存入store
              this.$store.commit('setMenu',data.data.menu);
              //当存入菜单后，动态注册路由,调用 addMenu
              this.$store.commit('addMenu',this.$router);
              // 跳转首页
              this.$router.push('home')
              this.$message.success('登录成功.');
            } else {
              this.$message.error('账号信息错误');
            }
          })
        }
      })
    },
    // 点击回车键登录
    keyDown(e) {
      // 回车则执行登录方法 enter键的ASCII是13
      if (e.keyCode == 13 || e.keyCode == 100) {
        this.submit(); // 定义的登录方法
      }
  },
  },

  mounted() {
    // 绑定监听事件
    window.addEventListener("keydown", this.keyDown);
  },
  destroyed() {
    // 销毁事件
    window.removeEventListener("keydown", this.keyDown, false);
  },
}
</script>
  
<style lang="less" scoped>
#poster {
  background: url("../assets/img/back.jpg") no-repeat;
  background-position: center;
  height: 100%;
  width: 100%;
  background-size: cover;
  position: fixed;

  .loginPage {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -150px;
    margin-left: -175px;
    width: 350px;
    min-height: 200px;
    padding: 30px 20px 20px;
    border-radius: 15px;
    box-sizing: border-box;
    background-color: #fff;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #303133;

    .login-title {
      text-align: center;
      margin: 0 auto 40px auto;
      color: #303133;
    }
  }
}
</style>